package com.edu.chat.web.covert;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import com.edu.buservice.util.model.TenantUtil;
import com.edu.chat.web.common.enums.ResultCodeEnum;
import com.edu.chat.web.common.model.BizException;
import com.edu.chat.web.controller.vo.LibraryVO;
import com.edu.chat.web.dto.LibraryInfoDTO;
import com.edu.chat.web.model.CsLibrary;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.function.Consumer;

/**
 * @program: KQAIA
 * @description:
 * @author: 无恙
 * @create: 2025-03-19 12:43
 **/

@Slf4j
public class LibraryCovert {

	public static CsLibrary convert(LibraryVO libraryVO) {
		CsLibrary csLibrary = new CsLibrary();
		csLibrary.setTitle(libraryVO.getName());
		csLibrary.setDescription(libraryVO.getDescription());
		csLibrary.setOpenSearch(libraryVO.getEnable() ? 1 : 0);
		csLibrary.setTenantId(TenantUtil.getTenantId());
		csLibrary.setCreatedBy(StpUtil.getLoginIdAsString());
		return csLibrary;
	}

	public static LibraryInfoDTO convert(CsLibrary csLibrary) {
		if (csLibrary == null) {
			throw new BizException(ResultCodeEnum.PARAM_INVALID);
		}

		LibraryInfoDTO libraryInfoDTO = new LibraryInfoDTO();

		// 封装字段赋值逻辑，减少重复代码
		setFieldIfNotNull(libraryInfoDTO::setId, Long.toString(csLibrary.getId()));
		setFieldIfNotNull(libraryInfoDTO::setName, csLibrary.getTitle());
		setFieldIfNotNull(libraryInfoDTO::setDescription, csLibrary.getDescription());
		libraryInfoDTO.setEnable(csLibrary.getOpenSearch() == 1);
		setFieldIfNotNull(libraryInfoDTO::setCreateTime, formatDateSafely(csLibrary.getCreatedAt()));
		setFieldIfNotNull(libraryInfoDTO::setUpdateTime, formatDateSafely(csLibrary.getUpdatedAt()));
		setFieldIfNotNull(libraryInfoDTO::setCreateBy, csLibrary.getCreatedBy());
		setFieldIfNotNull(libraryInfoDTO::setUpdateBy, csLibrary.getUpdatedBy());
		setFieldIfNotNull(libraryInfoDTO::setCount, csLibrary.getTotalArticles());

		return libraryInfoDTO;
	}

	// 辅助方法：安全设置字段值，避免空指针异常
	private static <T> void setFieldIfNotNull(Consumer<T> setter, T value) {
		if (value != null) {
			setter.accept(value);
		}
	}

	// 辅助方法：安全格式化日期，避免异常
	private static String formatDateSafely(Date date) {
		try {
			return DateUtil.format(date,"yyyy-MM-dd HH:mm:ss");
		} catch (Exception e) {
			// 记录日志并返回默认值或空字符串
			log.error("Failed to format date", e);
			return "";
		}
	}

}
